package com.iplay.service.query.and;

import java.util.List;
import java.util.Objects;
import java.util.Stack;

import com.iplay.service.query.Query;
import com.iplay.service.query.QueryCondition;

public class AndQuery extends Query {

	private List<QueryCondition> queryConditions;

	public AndQuery(List<QueryCondition> queryConditions) {
		Objects.requireNonNull(queryConditions);
		this.queryConditions = queryConditions;
	}

	@Override
	public QueryTreeNode buildQueryTree() {
		if (queryConditions.size() == 0)
			return null;
		Stack<QueryTreeNode> stack = new Stack<>();
		for (QueryCondition queryCondition : queryConditions) {
			stack.push(new QueryTreeNode(queryCondition));
		}
		while (stack.size() > 1) {
			QueryTreeNode left = stack.pop();
			QueryTreeNode right = stack.pop();
			QueryTreeNode newNode = new QueryTreeNode(LogicalOperator.AND, left, right);
			stack.push(newNode);
		}
		return stack.pop();
	}

}
